<?php
/**
 * Auther: Joshua Conero
 * Date: 2018/2/2 0002 23:41
 * Email: brximl@163.com
 * Name: 接口公共访问程序
 */

namespace App\Http\Controllers\Api;


use App\Http\Controllers\Controller;

class ApiBaseCtrl extends Controller
{
    protected $args;
    /**
     * @param $data mixed
     */
    protected function sendJson($data){
        header('Content-Type:application/json;charset=utf8;');
        if(is_array($data)){
            if(env('APP_DEBUG')){
                $data['time'] = date('Y-m-d H:i:s');
                $data['args'] = $this->args;
                $data['raw'] = request()->toArray();
                $data['user'] = $this->getUserInfo('user');
                // 错误捕捉失败
                $pigenos = $this->getPigeons();
                //$errMsg = $pigenos->getError();
                //if($errMsg) $data['pigeons_msg'] = $errMsg;
                if($pigenos->errorMsg) $data['pigeons_msg'] = $pigenos->errorMsg;
            }
            $data = json_encode($data);
        }
        echo $data;
        die;
    }

    /**
     * @param $msg
     * @param null $data
     */
    protected function error($msg, $data=null){
        $send = [
            'error' => 1,
        ];
        if(is_array($msg)){
            $send['data'] = $msg;
            $send['msg'] = '';
        }else{
            $send['msg'] = $msg;
        }
        if(is_array($data)) $send = array_merge($send, $data);
        $this->sendJson($send);
    }

    /**
     * @param string|array $msg
     * @param null $data
     */
    protected function success($msg, $data=null){
        $send = [
            'error' => 0,
        ];
        if(is_array($msg)){
            $send['data'] = $msg;
            $send['msg'] = '';
        }else{
            $send['msg'] = $msg;
        }
        if(is_array($data)) $send = array_merge($send, $data);
        $this->sendJson($send);
    }

    /**
     * 内部程序路由器
     * @param string $action => IndexAction
     */
    public function InnerRouter($action){
        $action = ucfirst($action).'Action';
        if(method_exists($this, $action)){
            call_user_func([$this, $action]);
        }else{
            $this->error('系统出错，请求方法不存在！');
        }
    }
}